import Vue from 'vue'
import Vuex from 'vuex'
//引入微擎配置
import util from '../static/js/util.js'
Vue.use(Vuex)

const store = new Vuex.Store({
	state: {
		openid: '',
		config: {},
		pageIndex: 0,
	},
	mutations: {
		setOpenid(state, openid) {
			state.openid = openid
		},
		setConfig(state, config) {
			state.config = config
		},
		setPageIndex(state, pageIndex) {
			state.pageIndex = pageIndex
		},
	},
    getters:{
        currentColor(state){
            return state.colorList[state.colorIndex]
        }
    },
	actions: {
		// lazy loading openid
		getUserOpenId: async function ({
			commit,
			state
		}) {
			return await new Promise((resolve, reject) => {
				if (state.openid) {
					resolve(state.openid)
				} else {
					uni.login({
						success: (data) => {
							commit('login')
							setTimeout(function () { //模拟异步请求服务器获取 openid
								const openid = '123456789'
								console.log('uni.request mock openid[' + openid + ']');
								commit('setOpenid', openid)
								resolve(openid)
							}, 1000)
						},
						fail: (err) => {
							console.log('uni.login 接口调用失败，将无法正常使用开放接口等服务', err)
							reject(err)
						}
					})
				}
			})
		},
		/**
		 * 全局配置
		 */
		setConfigAsync: async function ({
			commit,
			state
		}) {
			return await new Promise((resolve, reject) => {
				//TODO H5端各独立模块做个判断获取自身配置项，小程序端分包方式引入无需处理，配置项获取主包配置
				let m = util.m
				console.log(m)
				let m_config = 'muu_classroom_config'
				if(m == 'muu_classroom'){
					m_config = 'muu_classroom_config'
				}
				if(m == 'muu_minishop'){
					m_config = 'muu_minishop_config'
				}
				if(m == 'muu_scoreshop'){
					m_config = 'muu_scoreshop_config'
				}
				if(m == 'muu_activity'){
					m_config = 'muu_activity_config'
				}
				
				const config = uni.getStorageSync(m_config);
				if(config && config.deadtime){
					let newtime = Date.parse(new Date());
					if(config.deadtime < newtime){
						getApiData()
					}else{
						commit('setConfig', config.data)
						resolve(config)
					}
				}else{
					getApiData()
				}
				
				function getApiData(){
					let url = '';
						//#ifdef MP-WEIXIN
						url = 'entry/wxapp/config'
						//#endif
						//#ifdef H5
						url = 'entry/site/config'
						//#endif
					util.request({
						// 小程序端执行
						url : url,
						data: {
							action : '',
							m: m
						},
						success: function (res) {
							if (res.data.code == 200) {
								// 缓存 一个小时
								let deadtime = Date.parse(new Date()) + 3600 * 1000
								let page_data_store = {
									'deadtime' : deadtime,
									'data' : res.data.data
								}
								uni.setStorageSync(m_config, page_data_store)
								commit('setConfig', page_data_store.data)
								resolve(page_data_store)
							}
							resolve()
						}
					})
				}
			})
		}

	}
})

export default store
